package br.org.nomoney.vink.util.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectSerializationUtil implements ObjectToFromBytesConverter {

	private static ObjectToFromBytesConverter instance;
	
	public static ObjectToFromBytesConverter getInstance(){
		if (instance == null) {
			instance = new ObjectSerializationUtil();
		}
		return instance;
	}
	
	public byte[] fromObjectToBytes(Object obj) throws IOException {
		byte[] result = null;
		if (obj != null) {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream out = new ObjectOutputStream(bos);
			out.writeObject(obj);
			out.close();
			result = bos.toByteArray();
		}
		return result;
	}

	public Object fromBytesToObject(byte[] inContent)
			throws IOException, ClassNotFoundException {
		Object result = null;
		if (inContent != null) {

			ByteArrayInputStream bos = new ByteArrayInputStream(inContent);
			ObjectInputStream in = new ObjectInputStream(bos);
			result = in.readObject();
		}
		return result;
	}

}